package com.imooc.news_manager_project.service.impl;

import com.imooc.news_manager_project.common.CommonMethods;
import com.imooc.news_manager_project.common.Result;
import com.imooc.news_manager_project.domain.Comments;
import com.imooc.news_manager_project.domain.News;
import com.imooc.news_manager_project.dto.CommentsDTO;
import com.imooc.news_manager_project.mapper.CommentsRepository;
import com.imooc.news_manager_project.mapper.NewsRepository;
import com.imooc.news_manager_project.service.ICommentService;
import com.imooc.news_manager_project.utils.KeyHandleUtil;
import com.imooc.news_manager_project.utils.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class CommentsServiceImpl implements ICommentService {

    @Autowired
    private CommentsRepository commentsRepository;

    @Autowired
    private CommonMethods commonMethods;

    @Autowired
    private NewsRepository newsRepository;

    @Autowired
    private RedisUtil redisUtil;

    public List<Comments> getAllComments() {
        return commentsRepository.findAll();
    }

    public Result save(HttpServletRequest request, CommentsDTO commentsDTO) {
        Optional<News> newsOptional = newsRepository.findById(commentsDTO.getNewsId());

        if (newsOptional.isPresent()) {

            if (commentsDTO.getParentId() != null) {
                commentsDTO.setParentId("0");
            }

            Map loginUserInfo = commonMethods.getLoginUserInfo(request);
            Integer idCurrent = (Integer) loginUserInfo.get("id");
            Comments comments = new Comments();
            BeanUtils.copyProperties(commentsDTO, comments);
            comments.setUserId(idCurrent).setCreateTime(new Date());

            commentsRepository.insert(comments);

            if (comments.getId() != null) {
                return new Result(200, "评论成功", comments.getId());
            }
            return new Result(400, "评论失败");
        }
        return new Result(400, "新闻不存在");
    }

    public Result getAllNewsComments(String id) {
        Comments comments = new Comments();
        comments.setNewsId(id).setParentId("0");
        Example<Comments> commentsExample = Example.of(comments);
        List<Comments> all = commentsRepository.findAll(commentsExample);
        return new Result(200, "查询成功", all);
    }

    public Result getReplyComments(String id) {
        Comments comments = new Comments();
        comments.setParentId(id);
        Example<Comments> commentsExample = Example.of(comments);
        List<Comments> all = commentsRepository.findAll(commentsExample);
        return new Result(200, "查询成功", all);
    }

    private List<Comments> getComments(String id, List<Comments> commentsList) {
        Comments commentsQuery = new Comments();
        commentsQuery.setParentId(id);
        Example<Comments> commentsExample = Example.of(commentsQuery);
        List<Comments> lists = commentsRepository.findAll(commentsExample);
        commentsList.addAll(lists);
        for (Comments comment : lists) {
            getComments(comment.getId(), commentsList);
        }
        return commentsList;
    }

    public Result removeComments(String id) {
        Optional<Comments> commentsOptional = commentsRepository.findById(id);
        if (commentsOptional.isPresent()) {
            ArrayList<Comments> commentsArrayList = new ArrayList<>();
            List<Comments> comments = getComments(id, commentsArrayList);
            commentsArrayList.add(commentsOptional.get());
            commentsRepository.deleteAll(comments);
            return new Result(200, "删除成功");
        } else {
            return new Result(400, "删除失败，不存在");
        }
    }

    public Result likesById(HttpServletRequest request, String id) {
        String msg = "";
        // 验证是否存在对应id评论数据
        Optional<Comments> optionalComments = commentsRepository.findById(id);
        if (optionalComments.isPresent()) {
            //	获取当前登录用户的信息
            Map map = commonMethods.getLoginUserInfo(request);
            Integer userId = (Integer) map.get("id");
            //	定义 redis 评论点赞数据的key值格式
            // String key = "comments_likes_" + id;
            String key = KeyHandleUtil.handleCommentsLikeKey(id);
            boolean haveKey = redisUtil.hasKey(key);
            if (!haveKey) {
                //	该评论第一次点赞，保存点赞数据
                redisUtil.addSet(key, userId);
                msg = "点赞成功";
            } else {
                //	判断该用户是点赞还是取消点赞
                boolean resHava = redisUtil.hasMemberSet(key, userId);
                if (resHava) {
                    //	如果已经点过赞，则进行取消点赞
                    redisUtil.removeSet(key, userId);
                    msg = "取消点赞成功";
                } else {
                    redisUtil.addSet(key, userId);
                    msg = "点赞成功";
                }
            }
            Long resNum = redisUtil.countSet(key);
            return new Result(200, msg, resNum);
        } else {
            return new Result(400, "不存在对应id的评论数据");
        }
    }

}
